1-Dimensional Arrays in C

Introduction

A 1-dimensional array is a collection of elements stored in a contiguous memory block, where all elements are of the same data type. It allows you to store and access a sequence of values using a single index.

Declaration and Initialization

Declaration:

data_type array_name[size];
            

Examples:

int numbers[5]; // Array to store 5 integers

int numbers[5] = {1, 2, 3, 4, 5}; // Initializes the array with specific values

int numbers[] = {1, 2, 3, 4, 5}; // Size automatically set to 5
            

Accessing and Iterating Elements

Accessing array elements:

numbers[0] = 10;  // Assigns 10 to the first element
int x = numbers[2]; // Retrieves the third element
            

Iterating through a 1-D array:

#include  < stdio.h>

int main() {
    int numbers[5] = {10, 20, 30, 40, 50};

    for (int i = 0; i < 5; i++) {
        printf("numbers[%d] = %d\n", i, numbers[i]);
    }

    return 0;
}
            

Output:

numbers[0] = 10
numbers[1] = 20
numbers[2] = 30
numbers[3] = 40
numbers[4] = 50
            

Characteristics

Common Use Cases